<?php

namespace App\Http\Controllers;

use App\Models\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    // 显示任务列表
    public function index()
    {
        $tasks = Task::all();
        return view('tasks.index', compact('tasks'));
    }

    // 显示添加任务表单
    public function create()
    {
        return view('tasks.create');
    }

    // 保存新任务
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        Task::create($request->all());

        return redirect()->route('tasks.index')->with('success', '任务添加成功！');
    }

    // 显示编辑任务表单
    public function edit(Task $task)
    {
        return view('tasks.edit', compact('task'));
    }

    // 更新任务
    public function update(Request $request, Task $task)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        $task->update($request->all());

        return redirect()->route('tasks.index')->with('success', '任务更新成功！');
    }

    // 删除任务
    public function destroy(Task $task)
    {
        $task->delete();
        return redirect()->route('tasks.index')->with('success', '任务删除成功！');
    }
}